import React from 'react'
import { Text, View, ScrollView, TouchableOpacity, Platform, Alert, Image, ListView as RNList,AsyncStorage } from 'react-native'
import { AnimatedGaugeProgress } from 'react-native-simple-gauge'

import ToastUtils from '../../common/ToastUtils'
import Config from '../../config'
import SizeUtils from '../../common/SizeUtils'
import Constants from '../../common/Constants'
import { DateUtils } from '../../utils/Utils'
import BasePage from '../common/BasePage'
import CommonDataListView from '../common/CommonDataListView'
import TImage from '../../components/TImage'
import SportUserItem from './SportUserItem'
import SportGetStepConfigAction from '../../actions/sport/SportGetStepConfigAction'
import SportOptionsStepConfigAction from '../../actions/sport/SportOptionsStepConfigAction'
import SportSendStepAction from '../../actions/sport/SportSendStepAction'
import SportRequestUserListAction from '../../actions/sport/SportRequestUserListAction'
import SportRequestSelfDataAction from '../../actions/sport/SportRequestSelfDataAction'
import SportGetTodayStepsAction from '../../actions/sport/SportGetTodayStepsAction'
import SportSendActivityStepsAction from '../../actions/sport/SportSendActivityStepsAction'
import SportSendActivityStepsDailyAction from '../../actions/sport/SportSendActivityStepsDailyAction'
import CommonCheckUserTypeAction from '../../actions/common/CommonCheckUserTypeAction'
import ChangePageAction from '../../actions/common/ChangePageAction'
import ImageUtil from '../common/ImageUtil'
import UserRequestAPPConfigAction from '../../actions/user/UserRequestAPPConfigAction'
import BaseComponent from '../common/BaseComponent'
import CommonRequestSliderImagesAction from '../../actions/common/CommonRequestSliderImagesAction'
import ActivityRequestListAction from '../../actions/activity/ActivityRequestListAction'
import SportSettingView from './SportSettingView'
import SportInfoView from './SportInfoView'
import NoticeIcon from '../user/NoticeIcon'
import NoticeAdView from '../common/NoticeADView'

var ds = new RNList.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 })

//sportData
//DqappStepDetail {
// avatar_url (string, optional): 头像 ,
// by_name (string, optional): 用户名字 ,
// by_user_id (string, optional): 用户ID ,
// department (string, optional): 所属单位 ,
// steps (integer, optional): 步行数 ,
// updated_at (string, optional): 最后更新时间
// }

var BUTTONS = [
  { key: 'day_rank', name: '日排名', sort_id: 1, type: 1 },
  { key: 'week_rank', name: '周排名', sort_id: 1, type: 2 },
  { key: 'month_rank', name: '月排名', sort_id: 1, type: 3 },
  { key: 'danweiMonth_rank', name: '单位月排名', sort_id: 1, type: 3 }
]
var ACTIVITY_BUTTON = [
  { key: 'activity_day_rank', name: '日排名', sort_id: 1, type: 4 },
  { key: 'activity_week_rank', name: '周排名', sort_id: 1, type: 5 },
  { key: 'activity_month_rank', name: '月排名', sort_id: 1, type: 6 },
  { key: 'activity_danweiMonth_rank', name: '单位月排名', sort_id: 2, type: 6 }
]

const TOP_BUTTONS = [
  // {key:"youtian_dibiao", name:"油田地标", source:require("../../../resource/images/sport/icon_dibiao.png"),
  //   style:{width:64, height:80}, page:Config.pages.sport_dibiao_main},
  {
    key: 'gonggao',
    name: '通知公告',
    source: require('../../../resource/images/sport/tongzhi.png'),
    style: { width: 86, height: 86 },
    pageKey: Config.pages.sport_gonggao.key
  },
  { key: 'line' },
  {
    key: 'sprot_data',
    name: '运动数据',
    source: require('../../../resource/images/sport/shuju.png'),
    style: { width: 86, height: 86 },
    pageKey: Config.pages.sport_data.key
  },
  { key: 'line' },
  {
    key: 'submit',
    name: '提交步数',
    source: require('../../../resource/images/sport/tijiao.png'),
    style: { width: 86, height: 86 }
  }
]
export default class SportMainPage extends BasePage {
  constructor(props) {
    super(props)
    // this.state.pageName

    this._buttonWidth = SizeUtils.translateDesignWidthToCode(130)
    this._pageWidth = SizeUtils.getWindowSize().width - SizeUtils.translateDesignWidthToCode(20)
    this._scrollView = null

    // this._backgroudColor = "#65DAF8";
    this._fontColor = '#ffffff'

    this.state.sportData = {}
    this.state.sportData.by_name = '加载中'
    this.state.sportData.avatar_url = ''
    this.state.sportData.by_user_id = 0
    this.state.sportData.steps = 0
    this.state.sportData.show_submit_rank = -1

    this.state.showSetting = false
    this.state.showSportInfo = false
    this.state.aimSteps = 0

    this.state.sportInfo = {}

    this.state.listDatas = [
      {
        activity_id: '59f93273436fec1e0029267c',
        applicants_num: 21,
        begin_at: '2018-01-13 09:30:00',
        end_at: '2018-01-13 00:00:00',
        image_url:
          'http://dqapp.oss-cn-beijing.aliyuncs.com/media/5969951bd6b68ffda34751bb/AY6OC2743X51DSJMUQB8RQL11509503602673_.png',
        manner: 0,
        readers_num: 3196,
        tag: 1,
        time_state: 2,
        title: '了不起的大主播'
      },
      {
        activity_id: '59e8a9d6436fec2ecfa4133f',
        applicants_num: 0,
        begin_at: '2017-10-19 00:00:00',
        end_at: '2017-11-18 00:00:00',
        image_url:
          'http://dqapp.oss-cn-beijing.aliyuncs.com/media/59487d00d6b68ffda347459e/QLAV28BJBF5QVM7N6VP6NQBL1508460847430_.jpg',
        manner: 0,
        readers_num: 2566,
        tag: 1,
        time_state: 2,
        title: '“踏着铁人脚步走”线上活动来啦！零门槛、奖品炫~还不快来！'
      },
      {
        activity_id: '5a0265cd7a7ee010c2024942',
        applicants_num: 130,
        begin_at: '2018-01-08 19:00:00',
        end_at: '2018-01-21 21:00:00',
        image_url:
          'http://dqapp.oss-cn-beijing.aliyuncs.com/media/5969951bd6b68ffda34751bb/5RN4BNB6ERQW7IRN3Y1464Y51512123271635_.png',
        manner: 0,
        readers_num: 2118,
        tag: 1,
        time_state: 2,
        title: '全民斗地主大奖赛'
      },
      {
        activity_id: '59dc25b3436fec2f9a9cf5f5',
        applicants_num: 3,
        begin_at: '2017-10-10 18:25:02',
        end_at: '2017-10-10 19:00:16',
        image_url:
          'http://dqapp.oss-cn-beijing.aliyuncs.com/media/59720f63d6b68ffda34803be/XL9IS2MLONN7JMKN3W68ENP21507599793035_.png',
        manner: 0,
        readers_num: 1581,
        tag: 1,
        time_state: 2,
        title: '线上徒步大赛收官！神秘大奖，到底属于谁？'
      },
      {
        activity_id: '59f2e9317a7ee02925daac84',
        applicants_num: 11,
        begin_at: '2017-10-28 08:20:00',
        end_at: '2017-10-28 11:30:00',
        image_url:
          'http://dqapp.oss-cn-beijing.aliyuncs.com/media/59720f63d6b68ffda34803be/16KSSO2DEPRCEGL8LBKJCZ911509091631775_.jpg',
        manner: 0,
        readers_num: 1465,
        tag: 1,
        time_state: 2,
        title: '大庆石油人豪迈走向新时代！'
      },
      {
        activity_id: '59df75e7436fec41ddf18f9d',
        applicants_num: 1,
        begin_at: '2017-10-13 08:30:00',
        end_at: '2017-10-13 12:00:00',
        image_url:
          'http://dqapp.oss-cn-beijing.aliyuncs.com/media/596ddc98d6b68ffda3475c2b/3L1INWB1XEB3Y5Y11H7RNQU31507816935288_.jpg',
        manner: 0,
        readers_num: 1098,
        tag: 1,
        time_state: 2,
        title: '聆听石油人饱含深情的震撼发声！'
      }
    ]

    this.state.submitStepSuccess = false
    this.state.updateSelfData = false
    this.state.submitMark = false
    this.state.buttonDatas = []
    this.state.statusText = ''
    this.state.healthyData = null

    this.state.updateMark = 0
    this.state.scrollEnabled = Platform.OS === 'ios'

    this._clickTopBtnTimer = null
    this._getStepTimer = null
  }

  componentWillUpdate(nextProps, nextState) {
    super.componentWillUpdate(nextProps, nextState)
    if (nextState.statusText != '') {
      ToastUtils.show(nextState.statusText)
      nextState.statusText = ''
    }
    if (this.state.sportData.show_submit_rank != nextState.sportData.show_submit_rank) {
      // nextState.buttonDatas = BUTTONS.concat();
      if (nextState.sportData.show_submit_rank === 1) {
        nextState.buttonDatas = ACTIVITY_BUTTON
        nextState.selelctedType = nextState.buttonDatas[0].key
      } else {
        nextState.buttonDatas = []
        nextState.selelctedType - 1
      }
    }
    if (nextState.submitStepSuccess === true) {
      ToastUtils.show('提交成功')
      nextState.submitStepSuccess = false
      var obj = nextState.sportData;
      obj.is_submit=1;
      nextState.sportData=obj;
      nextState.submitMark = true
      // new SportRequestSelfDataAction().call(this);
    }
    if (nextState.updateSelfData === true) {
      nextState.updateSelfData = false
      nextState.submitMark = false
    }
  }

  componentDidMount() {
    const that = this;
    AsyncStorage.getItem('aimSteps',function (errs,result) {
      if (result) {
        that.setState({
          aimSteps:result 
        });
      }
    })
    this._initSendStepTimer()
    this._requestAPPConfig()
    this._requestSportConfig()
    this._requestData()
  }

  goBack() {
    if (this.state.leave === false) {
      new ChangePageAction().call(this, { type: 'goBack', prePageObj: this })
    } else {
      ImageUtil.uploadError('Error:SportMainPage goBack at this.state.leave === false')
    }
  }

  _requestSportConfig() {
    new SportGetStepConfigAction().call(this, {})
  }

  _requestAPPConfig() {
    // 废弃
    // new UserRequestAPPConfigAction().call(this, {
    //   key: Constants.CONFIG_NAME.SPORT_DIBIAO.key,
    //   requestType: "config"
    // });
  }
  _requestData() {
    new ActivityRequestListAction().call(this, {
      page: 1,
      page_size: 20,
      tag: 0,
      home_page: 1
    })
  }

  _dealEnterPage() {
    super._dealEnterPage()
    this.state.updateMark += 1
    this._initSendStepTimer()
    this._requestAPPConfig()
  }

  _initSendStepTimer() {
    if (this._getStepTimer == null) {
      this._getStepTimer = setInterval(() => {
        this._dealSendStepTimer()
      }, 5000)
    }
    this._dealSendStepTimer()
  }

  _dealSendStepTimer() {
    new SportRequestSelfDataAction().call(this)
    new SportGetTodayStepsAction().call(this)
  }

  _dealLeavePage() {
    super._dealLeavePage()
    this._clearInterval()
  }

  _clearInterval() {
    if (this._getStepTimer != null) {
      clearInterval(this._getStepTimer)
      this._getStepTimer = null
    }
  }

  showSetting = () => {
    console.log(this._sportsetting)
    this._sportsetting&&this._sportsetting.openSteps(this.state.aimSteps);
    this.setState({ showSetting: true })
  }

  closeSetting = () => {
    this.setState({ showSetting: false })
  }

  confirmSetting = steps => {
    AsyncStorage.setItem('aimSteps',''+steps);
    this.setState({ showSetting: false, aimSteps: steps })
    if (this.state.sportInfo.age == '' || this.state.sportInfo.height == '' || this.state.sportInfo.weight == '') {
      ToastUtils.show('个人信息不完整,提交失败')
      return
    }
    new SportOptionsStepConfigAction().call(this, {
      ...this.state.sportInfo,
      goal: steps,
      gender: Constants.USER.gender || 1
    })
  }

  showSportInfo = () => {
    // this.setState({ showSportInfo: true });
  }

  closeSportInfo = () => {
    // this.setState({ showSportInfo: false });
  }

  confirmSportInfo = ({ height, weight, age }) => {
    console.log('confirmSportInfoconfirmSportInfo', height, weight, age)
    this.setState({ sportInfo: { age, height, weight } })
    new SportOptionsStepConfigAction().call(this, {
      age,
      height,
      weight,
      goal: this.state.aimSteps,
      gender: Constants.USER.gender || 1
    })
  }

  render() {
    return (
      <View
        style={{
          width: SizeUtils.getWindowSize().width,
          height: SizeUtils.getWindowSize().height,
          paddingTop: Config.paddingTop
        }}
      >
        <ScrollView
          style={{
            flex: 1,
            backgroundColor: '#F2F2F2',
            height: SizeUtils.getWindowSize().height - Config.paddingTop
          }}
        >
          {this._renderTopView()}
          <NoticeAdView txt="文字广告轮播" tag={4} />
          {/* {this._renderActivityView()} */}
          {this._renderHeader('排行榜', '')}
          {this._renderListView()}
        </ScrollView>
          <SportSettingView ref={ref => (this._sportsetting = ref)} showSetting={this.state.showSetting} closeSetting={this.closeSetting} confirmSetting={this.confirmSetting} />
        {false&& (
          <SportInfoView closeSportInfo={this.closeSportInfo} confirmSportInfo={this.confirmSportInfo} />
        )}
        {this._renderNavigationBar()}
      </View>
    )
  }

  _renderNavigationBarRightButtonContent() {
    return (
      <View style={{ flexDirection: 'row', alignItems: 'center' }}>
        {/* <TouchableOpacity
          style={{
            marginRight: SizeUtils.translateDesignWidthToCode(10),
            height: SizeUtils.translateDesignHeightToCode(38),
            width: SizeUtils.translateDesignWidthToCode(113),
            alignItems: "center",
            justifyContent: "center",
            borderRadius: SizeUtils.translateDesignHeightToCode(19),
            borderWidth: SizeUtils.translateDesignNumToCode(3),
            borderColor: "#ffffff",
            backgroundColor: "#0000"
          }}
          onPress={this.showSportInfo}
        >
          <Text
            style={{
              color: "#ffffff",
              fontSize: SizeUtils.translateFontSizeToCode(22)
            }}
          >
            个人信息
          </Text>
        </TouchableOpacity> */}
        <NoticeIcon
          isWhite={true}
          backgroudColor={this._backgroudColor}
          fontColor={this._fontColor}
          authorization={this.props.authorization}
        />
      </View>
    )
  }

  _renderActivityView() {
    return (
      <View style={{ marginTop: SizeUtils.translateDesignHeightToCode(20) }}>
        {this._renderHeader('活动', '更多活动 > ')}
        <RNList
          horizontal={true}
          showsVerticalScrollIndicator={false}
          enableEmptySections={true}
          showsHorizontalScrollIndicator={false}
          style={{
            backgroundColor: '#fff',
            paddingLeft: SizeUtils.translateDesignWidthToCode(15),
            marginBottom: SizeUtils.translateDesignHeightToCode(20)
          }}
          dataSource={ds.cloneWithRows(this.state.listDatas)}
          renderRow={this._renderRow.bind(this)}
        />
      </View>
    )
  }

  _getImageSource(data) {
    if (data.avatar_url) {
      return { uri: data.avatar_url }
    } else {
      return { uri: '' }
    }
  }

  _renderRow(data) {
    return (
      <View
        style={{
          width: SizeUtils.translateDesignWidthToCode(200),
          height: SizeUtils.translateDesignHeightToCode(228),
          justifyContent: 'center',
          borderWidth: SizeUtils.translateDesignNumToCode(3),
          borderColor: '#eeeeee',
          borderRadius: 3,
          marginLeft: SizeUtils.translateDesignWidthToCode(14)
        }}
      >
        <TImage
          source={{ uri: data.image_url }}
          style={{ width: 200, height: 136 }}
          resizeMode={'cover'}
          isMini={true}
        />
        <View
          style={{
            height: SizeUtils.translateDesignHeightToCode(49),
            width: SizeUtils.translateDesignWidthToCode(200),
            alignItems: 'center',
            justifyContent: 'center',
            backgroundColor: '#ffffff'
          }}
        >
          <Text
            numberOfLines={1}
            style={{
              color: '#000000',
              fontSize: SizeUtils.translateFontSizeToCode(22),
              width: SizeUtils.translateDesignWidthToCode(180)
            }}
          >
            {data.title}
          </Text>
        </View>
      </View>
    )
  }

  _renderHeader(title, moreStr) {
    return (
      <View
        style={{
          flexDirection: 'row',
          paddingLeft: SizeUtils.translateDesignWidthToCode(30),
          paddingRight: SizeUtils.translateDesignWidthToCode(30),
          paddingBottom: SizeUtils.translateDesignHeightToCode(20),
          justifyContent: 'space-between',
          paddingTop: SizeUtils.translateDesignHeightToCode(30),
          alignItems: 'center',
          backgroundColor: '#ffffff'
        }}
      >
        <View style={{ flexDirection: 'row', alignItems: 'center' }}>
          <TImage source={require('../../../resource/images/home/biaotitle.png')} style={{ width: 8, height: 30 }} />
          <Text
            style={{
              fontSize: SizeUtils.translateFontSizeToCode(28),
              color: '#333333',
              marginLeft: SizeUtils.translateDesignWidthToCode(8),
              borderWidth: 0,
              backgroundColor: '#00000000',
              fontWeight: 'bold'
            }}
          >
            {title}
          </Text>
        </View>
        <TouchableOpacity disabled={!moreStr} onPress={this._onPressMore.bind(this)}>
          <Text
            style={{
              fontSize: SizeUtils.translateFontSizeToCode(24),
              color: '#888888'
            }}
          >
            {moreStr}
          </Text>
        </TouchableOpacity>
      </View>
    )
  }

  _onPressMore() {
    this.gotoPage(Config.pages.activity)
  }

  _renderTopView() {
    return (
      <View
        style={{
          height: SizeUtils.translateDesignHeightToCode(800)
        }}
      >
        <View
          style={{
            height: SizeUtils.translateDesignHeightToCode(700),
            backgroundColor: '#0000'
          }}
        >
          <Image
            style={{
              height: SizeUtils.translateDesignHeightToCode(700),
              position: 'absolute'
            }}
            source={require('../../../resource/images/sport/sportbg.jpg')}
          />
          <View
            style={{
              height: SizeUtils.translateDesignHeightToCode(540),
              alignItems: 'center'
            }}
          >
            <AnimatedGaugeProgress
              style={{
                position: 'absolute',
                marginTop: SizeUtils.translateDesignHeightToCode(28)
              }}
              size={SizeUtils.translateDesignWidthToCode(500)}
              width={SizeUtils.translateDesignWidthToCode(28)}
              fill={80}
              rotation={90}
              cropDegree={90}
              tintColor="#ffffff"
              backgroundColor="#F6A6A7"
              strokeCap="circle"
            />
            <View
              style={{
                height: SizeUtils.translateDesignWidthToCode(500),
                width: SizeUtils.translateDesignWidthToCode(500),
                alignItems: 'center'
              }}
            >
              <Text
                style={{
                  color: '#ffffff',
                  fontSize: SizeUtils.translateFontSizeToCode(140),
                  marginTop: SizeUtils.translateDesignHeightToCode(181)
                }}
              >
                {this.state.healthyData == null ? this.state.sportData.steps : this.state.healthyData.step}
              </Text>
              <View
                style={{
                  flexDirection: 'row',
                  height: SizeUtils.translateDesignHeightToCode(30),
                  alignItems: 'center',
                  marginTop: SizeUtils.translateDesignHeightToCode(26)
                }}
              >
                <Text
                  style={{
                    color: '#ffffff',
                    fontSize: SizeUtils.translateFontSizeToCode(26)
                  }}
                >
                  {`今日目标${this.state.aimSteps}步`}
                </Text>
                <TouchableOpacity
                  style={{
                    height: SizeUtils.translateDesignHeightToCode(26),
                    width: SizeUtils.translateDesignWidthToCode(63),
                    borderRadius: SizeUtils.translateDesignHeightToCode(13),
                    borderColor: '#ffffff',
                    backgroundColor: '#0000',
                    borderWidth: SizeUtils.translateDesignNumToCode(3),
                    alignItems: 'center',
                    justifyContent: 'center'
                  }}
                  onPress={this.showSetting}
                >
                  <Text
                    style={{
                      color: '#ffffff',
                      fontSize: SizeUtils.translateFontSizeToCode(18)
                    }}
                  >
                    设置
                  </Text>
                </TouchableOpacity>
              </View>
              <View style={{ flex: 1 }} />
              <TouchableOpacity
                style={{
                  height: SizeUtils.translateDesignHeightToCode(62),
                  width: SizeUtils.translateDesignWidthToCode(214),
                  borderRadius: SizeUtils.translateDesignHeightToCode(31),
                  borderColor: '#ffffff',
                  backgroundColor: '#0000',
                  borderWidth: SizeUtils.translateDesignNumToCode(6),
                  alignItems: 'center',
                  justifyContent: 'center',
                  marginBottom: SizeUtils.translateDesignHeightToCode(20)
                }}
                onPress={() => {
                  this._onPressSendStepBtn()
                }}
              >
                <Text
                  style={{
                    fontSize: SizeUtils.translateFontSizeToCode(28),
                    color: '#ffffff'
                  }}
                >
                  提交步数
                </Text>
              </TouchableOpacity>
            </View>
          </View>
          <View
            style={{
              height: SizeUtils.translateDesignHeightToCode(50),
              alignItems: 'center',
              justifyContent: 'center'
            }}
          >
            <Text
              style={{
                fontSize: SizeUtils.translateFontSizeToCode(24),
                color: '#ffffff'
              }}
            >{`提交步数可参加活动 ${this._getShowSubmitTime()}`}</Text>
          </View>
          <View
            style={{
              height: SizeUtils.translateDesignHeightToCode(100),
              flexDirection: 'row'
            }}
          >
            <View style={{ flex: 1, alignItems: 'center' }}>
              <Text
                style={{
                  color: '#f5fdff',
                  fontSize: SizeUtils.translateFontSizeToCode(48)
                }}
              >
                {this.state.healthyData&&this.state.healthyData.distance.toFixed(1)||0}
              </Text>
              <Text
                style={{
                  color: '#F7A4A5',
                  fontSize: SizeUtils.translateFontSizeToCode(28)
                }}
              >
                步行公里  
              </Text>
            </View>
            <View style={{ flex: 1, alignItems: 'center' }}>
              <Text
                style={{
                  color: '#f5fdff',
                  fontSize: SizeUtils.translateFontSizeToCode(48)
                }}
              >
                {this.state.healthyData&&(this.state.healthyData.step/20000).toFixed(3)||0}
              </Text>
              <Text
                style={{
                  color: '#F7A4A5',
                  fontSize: SizeUtils.translateFontSizeToCode(28)
                }}
              >
                消耗大卡
              </Text>
            </View>
          </View>
        </View>
        <View
          style={{
            position: 'absolute',
            bottom: SizeUtils.translateDesignHeightToCode(Platform.OS === 'ios'?17:34),
            height: SizeUtils.translateDesignHeightToCode(116),
            width: SizeUtils.getWindowSize().width,
            flexDirection: 'row',
            alignItems: 'center',
            justifyContent: 'center'
          }}
        >
          <TouchableOpacity
            onPress={() => this._onPressAnalysisButton(0)}
            style={{
              width: SizeUtils.translateDesignWidthToCode(336),
              height: SizeUtils.translateDesignHeightToCode(80),
              borderRadius: SizeUtils.translateDesignHeightToCode(40),
              backgroundColor: '#ffffff',
              alignItems: 'center',
              justifyContent: 'center',
              marginRight: SizeUtils.translateDesignWidthToCode(20)
            }}
          >
            <Text
              style={{
                color: '#ED494C',
                fontSize: SizeUtils.translateFontSizeToCode(30)
              }}
            >
              步数分析
            </Text>
          </TouchableOpacity>
          <TouchableOpacity
            onPress={() => this._onPressAnalysisButton(1)}
            style={{
              width: SizeUtils.translateDesignWidthToCode(336),
              height: SizeUtils.translateDesignHeightToCode(80),
              borderRadius: SizeUtils.translateDesignHeightToCode(40),
              backgroundColor: '#ffffff',
              alignItems: 'center',
              justifyContent: 'center'
            }}
          >
            <Text
              style={{
                color: '#ED494C',
                fontSize: SizeUtils.translateFontSizeToCode(30)
              }}
            >
              消耗大卡分析
            </Text>
          </TouchableOpacity>
        </View>
      </View>
    )
  }

  _renderTop2View() {
    return (
      <View style={{ height: SizeUtils.translateDesignHeightToCode(350) }}>
        {this._renderSelfView()}
        {/* {this._renderPageButtons()} */}
      </View>
    )
  }

  _renderSelfView() {
    return (
      <View
        style={{
          marginTop: SizeUtils.translateDesignHeightToCode(38),
          height: SizeUtils.translateDesignWidthToCode(108),
          paddingLeft: SizeUtils.translateDesignWidthToCode(60),
          flexDirection: 'row',
          justifyContent: 'space-between',
          alignItems: 'center'
        }}
      >
        <View style={{ flexDirection: 'row' }}>
          <TImage
            style={{
              width: 108,
              height: 108,
              borderRadius: 108,
              borderWidth: 1,
              borderColor: '#cccccc',
              overflow: 'hidden'
            }}
            source={{ uri: this.state.sportData.avatar_url }}
          />
          <View
            style={{
              flexDirection: 'column',
              paddingLeft: SizeUtils.translateDesignWidthToCode(40)
            }}
          >
            <View style={{ flexDirection: 'row' }}>
              <Text
                style={{
                  fontSize: SizeUtils.translateFontSizeToCode(24),
                  color: '#ffffff'
                }}
              >
                {this.state.sportData.by_name + '      今天步数  '}
                <Text
                  style={{
                    fontSize: SizeUtils.translateFontSizeToCode(50),
                    color: '#f6b64b'
                  }}
                >
                  {this.state.healthyData == null ? this.state.sportData.steps : this.state.healthyData.step}
                </Text>
                {'  步'}
              </Text>
            </View>
            <View
              style={{
                flexDirection: 'row',
                paddingTop: SizeUtils.translateDesignHeightToCode(10)
              }}
            >
              <Text
                style={{
                  fontSize: SizeUtils.translateFontSizeToCode(24),
                  color: '#ffffff',
                  textAlign: 'center'
                }}
              >
                {'提交步数可参加活动 ' + this._getShowSubmitTime() + '\n' + '(注意：此功能会收集您的设备步数)'}
              </Text>
            </View>
          </View>
        </View>
      </View>
    )
  }

  _getSubmited() {
    return this.state.submitMark == true || this.state.sportData.is_submit == 1
  }

  _getShowSubmitTime() {
    if (this.state.sportData.submit_begin_time) {
      return this.state.sportData.submit_begin_time + ' - ' + this.state.sportData.submit_end_time
    }
    return '00:00 - 00:00'
  }

  _onPressSendStepBtn() {
    new CommonCheckUserTypeAction().call(this.caller, { needLogin: true, needVerify: true }, () =>
      this._onCheckUserTypeCallback()
    )
  }

  _onCheckUserTypeCallback() {
    var nowDate = DateUtils.getNow()
    var beginDate = DateUtils.getDate(this.state.sportData.submit_begin_time)
    var endDate = DateUtils.getDate(this.state.sportData.submit_end_time)
    var step = this.state.healthyData == null ? this.state.sportData.steps : this.state.healthyData.step
    if (this._compareDate(beginDate, nowDate) === true || this._compareDate(nowDate, endDate) === true) {
      ToastUtils.show(
        '亲，不在提交时间内 ' +
          beginDate.hoursStr +
          ':' +
          beginDate.minutesStr +
          '~' +
          endDate.hoursStr +
          ':' +
          endDate.minutesStr
      )
    } else if (step < this.state.sportData.submit_min_steps) {
      ToastUtils.show('亲，你还没达到提交的最小步数(' + this.state.sportData.submit_min_steps + ')噢')
    } else if (this.state.sportData.submit_open == 0) {
      //是否允许提交，0否，1是 = ['0', '1'],
      ToastUtils.show('当前不允许提交')
    } else if (this.state.sportData.is_submit == 1) {
      //是否已提交，0否，1是 = ['0', '1'],
      ToastUtils.show('亲，你已提交步数，不能重复提交')
    } else {
      Alert.alert('提示', '是否确认提交步数，每天只能提交一次', [
        {
          text: '确定',
          onPress: () => {
            new SportSendActivityStepsAction().call(this, { steps: step })
          }
        },
        { text: '取消', onPress: () => {} }
      ])
    }
  }

  _compareDate(leftDate, rightDate) {
    if (leftDate.hours > rightDate.hours) {
      return true
    } else if (leftDate.hours == rightDate.hours && leftDate.minutes > rightDate.minutes) {
      return true
    } else if (
      leftDate.hours == rightDate.hours &&
      leftDate.minutes == rightDate.minutes &&
      leftDate.seconds > rightDate.seconds
    ) {
      return true
    }
    return false
  }

  _renderPageButtons() {
    return (
      <View style={{ marginTop: SizeUtils.translateDesignHeightToCode(20) }}>
        {/* <View style={{flexDirection:"row", borderBottomWidth:SizeUtils.translateDesignNumToCode(3),
            justifyContent:"center", alignItems:"center",
            borderColor:"#9ea3a4"}}>
          {this._renderPageButton(BUTTONS[0], true, true)}
          {this._renderPageButton(BUTTONS[1], false, true)}
        </View> */}
        <View
          style={{
            flexDirection: 'row',
            justifyContent: 'space-around',
            alignItems: 'center',
            height: SizeUtils.translateDesignHeightToCode(170)
          }}
        >
          {TOP_BUTTONS.map((data, index) => {
            return this._renderPageButton(data, index, false)
          })}
        </View>
      </View>
    )
  }

  _renderPageButton(data, index) {
    if (data.key == 'line') {
      return (
        <View
          key={index}
          style={{
            height: SizeUtils.translateDesignHeightToCode(100),
            width: SizeUtils.translateDesignNumToCode(3),
            backgroundColor: '#9ea3a4'
          }}
        />
      )
    } else {
      return (
        <TouchableOpacity
          key={index}
          style={{
            width: this._buttonWidth,
            flexDirection: 'column',
            alignItems: 'center'
          }}
          disabled={this._checkDisabled(data)}
          onPress={() => this._onPressPageButton(data)}
        >
          <View style={{}}>
            <TImage source={data.source} style={data.style} />
          </View>
          <Text
            style={{
              fontSize: SizeUtils.translateFontSizeToCode(26),
              color: '#ffffff',
              textAlign: 'center',
              fontWeight: 'bold',
              paddingTop: SizeUtils.translateDesignHeightToCode(20)
            }}
          >
            {data.key === TOP_BUTTONS[4].key ? (this._getSubmited() ? '已提交' : '提交步数') : data.name}
          </Text>
        </TouchableOpacity>
      )
    }
  }

  _checkDisabled(data) {
    switch (data.key) {
      case TOP_BUTTONS[0].key:
        //  ToastUtils.show("该功能暂未开放");
        return false
        break
      case TOP_BUTTONS[2].key:
        return false
        break
      case TOP_BUTTONS[4].key:
        return this._getSubmited()
        break
    }
    return false
  }

  _onPressAnalysisButton(index) {
    this.gotoPage(Config.getPageDataByKey(TOP_BUTTONS[2].pageKey), {
      currentIndex: index
    })
  }

  _onPressPageButton(data) {
    switch (data.key) {
      case TOP_BUTTONS[0].key:
        // if(this.state.configDataDic[Constants.CONFIG_NAME.SPORT_DIBIAO.key] === "1") {
        this.gotoPage(Config.getPageDataByKey(TOP_BUTTONS[0].pageKey))
        // }
        // else {
        // ToastUtils.show("该功能暂未开放");
        // }
        break
      case TOP_BUTTONS[2].key:
        this.gotoPage(Config.getPageDataByKey(TOP_BUTTONS[2].pageKey))
        break
      case TOP_BUTTONS[4].key:
        this._onPressSendStepBtn()
        break
    }
  }

  _renderListView() {
    let height = SizeUtils.getWindowSize().height - SizeUtils.translateDesignHeightToCode(350 + 10) - Config.paddingTop
    return (
      <View
        style={{
          backgroundColor: '#ffffff',
          // borderRadius: SizeUtils.translateDesignNumToCode(30),
          width: SizeUtils.getWindowSize().width,
          height: height
        }}
      >
        <View
          style={{
            paddingLeft: SizeUtils.translateDesignWidthToCode(32),
            flexDirection: 'row',
            height: SizeUtils.translateDesignHeightToCode(50),
            marginTop: SizeUtils.translateDesignHeightToCode(30)
          }}
        >
          {this.state.buttonDatas.map((data, index) => {
            return this._renderTypeButton(data, index)
          })}
        </View>
        <ScrollView
          style={{
            width: this._pageWidth,
            height: height - 100
          }}
          ref={ref => (this._scrollView = ref)}
          horizontal={true} // 水平方向
          showsHorizontalScrollIndicator={false} // 水平指示器
          showsVerticalScrollIndicator={false} // 垂直指示器
          pagingEnabled={true} // 开启分页功能
          alwaysBounceHorizontal={false} //弹性拉动一截
          onScroll={this._onScroll.bind(this)}
          scrollEventThrottle={16}
          scrollEnabled={this.state.scrollEnabled}
        >
          {this.state.buttonDatas.map((data, index) => {
            return this._renderListItem(data, index, height)
          })}
        </ScrollView>
      </View>
    )
  }

  _renderListItem(buttonData, index, height) {
    return (
      <ListView
        key={index}
        style={{
          width: this._pageWidth,
          height: height - SizeUtils.translateDesignHeightToCode(100)
        }}
        typeData={buttonData}
        updateMark={this.state.updateMark}
        isSelected={buttonData.key === this.state.selelctedType}
      />
    )
  }

  _onScroll(event) {
    let x = event.nativeEvent.contentOffset.x
    let index = Math.round(x / this._pageWidth)
    // console.log("round", index, x / this._pageWidth, x, this._pageWidth);
    let type = this.state.buttonDatas[index]
    if (this.state.selelctedType != type.key) {
      this.setState({
        selelctedType: type.key
      })
    }
  }

  _renderTypeButton(data, index) {
    return (
      <TouchableOpacity
        key={index}
        onPress={() => this._onPressTypeButton(data)}
        style={{
          flex: 1,
          borderColor: '#6bcdf4',
          alignItems: 'center',
          justifyContent: 'center'
          // borderBottomWidth:
          //   this.state.selelctedType === data.key
          //     ? SizeUtils.translateDesignNumToCode(3)
          //     : 0
          // marginRight: SizeUtils.translateDesignWidthToCode(26)
        }}
      >
        <Text
          style={{
            fontSize: SizeUtils.translateFontSizeToCode(26),
            color: this.state.selelctedType === data.key ? '#EE3535' : '#000000'
          }}
        >
          {data.name}
        </Text>
      </TouchableOpacity>
    )
  }

  _onPressTypeButton(data) {
    let index = this.state.buttonDatas.indexOf(data)
    this._clickTopBtnTimer = setTimeout(() => {
      this.setState({
        scrollEnabled: Platform.OS === 'ios'
      })
      this._clearClickTopBtnTimer()
    }, 500)
    this.setState(
      {
        scrollEnabled: true
      },
      () => this._scrollView.scrollTo({ x: index * this._pageWidth })
    )
  }

  _clearClickTopBtnTimer() {
    this._clickTopBtnTimer && clearTimeout(this._clickTopBtnTimer)
    this._clickTopBtnTimer = null
  }
}

// DqappStepDetail
// {
// "self_step": {
//   "avatar_url": "://",
//   "by_name": "Nihil quisquam est fugit id.",
//   "by_user_id": "2vm9xnb9hf",
//   "department": "Qui quasi assumenda.",
//   "steps": 1,
//   "updated_at": "2006-01-02 15:04:05"
// self_rank:0,
// },
// "step_list": [
//   {
//     "avatar_url": "://",
//     "by_name": "Nihil quisquam est fugit id.",
//     "by_user_id": "2vm9xnb9hf",
//     "department": "Qui quasi assumenda.",
//     "steps": 1,
//     "updated_at": "2006-01-02 15:04:05"
//     "rank":0,
//   }
// ]
// }
class ListView extends CommonDataListView {
  constructor(props) {
    super(props)

    this._itemClickEnable = false
    this._noEmpty = true
    this._initSelfStep(this.state)
    this.state.isSelected = this.props.isSelected === true
  }

  _dealComponentWillUpdate(nextProps, nextState) {
    nextState.isSelected = nextProps.isSelected
    if (this._pullRefresh && this.props.isSelected === false && nextProps.isSelected === true) {
      this.doRefresh()
    }
    if (this._pullRefresh && nextProps.isSelected === true && nextProps.updateMark != this.props.updateMark) {
      this.doRefresh()
    }

    if (nextState.isResponeUpdate && this._pullRefresh) {
      console.log('shouldComponentUpdate ResponeUpdate', nextState.data)
      this._initSelfStep(nextState)
      nextState.isResponeUpdate = false
      // nextState.data.self_step.rank = nextState.data.self_step.self_rank;
      this._pullRefresh.finish(1, nextState.data.step_list)
    }
  }

  _initSelfStep(state) {
    if (state.data.self_step == {} || state.data.self_step === undefined) {
      state.data.self_step = {
        avatar_url: '',
        by_name: '',
        by_user_id: '',
        department: '',
        steps: 0,
        updated_at: '',
        self_rank: 0,
        rank: 0
      }
    } else if (state.data.self_step.by_user_id == '' && this.state.data.self_step.by_user_id != '') {
      state.data.self_step = this.state.data.self_step
    }
  }

  render() {
    if (this.state.isSelected === true) {
      return super.render()
    } else {
      return (
        <View
          style={{
            flexDirection: 'row',
            alignItems: 'center',
            width: this.props.style.width,
            justifyContent: 'space-between',
            height: SizeUtils.translateDesignHeightToCode(140),
            borderColor: '#eeeeee',
            paddingLeft: SizeUtils.translateDesignWidthToCode(35),
            paddingRight: SizeUtils.translateDesignWidthToCode(32),
            borderBottomWidth: SizeUtils.translateFontSizeToCode(3)
          }}
        />
      )
    }
  }

  _onRenderHeader() {
    return <SportUserItem index={0} data={this.state.data.self_step} style={{ width: this.props.style.width }} />
  }

  _onRenderItem(data, index) {
    return <SportUserItem key={index} index={index + 1} data={data} style={{ width: this.props.style.width }} />
  }

  _requestData(page) {
    //排序方式，1油田内，2部门内
    if (page > 10) {
      let timer = setTimeout(() => {
        clearTimeout(timer)
        this._pullRefresh && this._pullRefresh.finish(1, [])
      }, 1000)
    } else {
      new SportRequestUserListAction().call(this, {
        page: page,
        sort_id: this.props.typeData.sort_id,
        type: this.props.typeData.type,
        page_size: 10
      })
    }
  }
}
